<template>
  <div class="website-tracking-container">
    <h2 style="margin-bottom: 24px">网站访问统计</h2>

    <!-- 日志统计概览 -->
    <LogStatsOverview 
      :log-stats="logStats"
      :is-loading="isLoading"
    />

    <!-- 网站列表表格 -->
    <WebsiteTable 
      :websites="websites"
      :is-loading="isLoading"
      :current-website-id="currentWebsite?._id"
      @add-website="handleAddWebsite"
      @view-stats="handleViewStats"
      @view-logs="handleViewLogs"
      @get-embed-code="handleGetEmbedCode"
      @update-website="handleUpdateWebsite"
      @delete-website="handleDeleteWebsite"
      @delete-all-websites="handleDeleteAllWebsites"
    />

    <!-- 标签页 -->
    <el-tabs 
      v-model="activeTab" 
      type="card"
      style="margin-top: 24px"
    >
      <el-tab-pane label="统计概览" name="overview">
        <!-- 统计数据展示 -->
        <StatsDisplay 
          v-if="currentWebsite"
          :website="currentWebsite"
          :time-range="statsParams.timeRange"
          :group-by="statsParams.groupBy"
          @time-range-change="handleTimeRangeChange"
          @group-by-change="handleGroupByChange"
        />

        <!-- 业务闭环检测 -->
        <BusinessLoopDisplay 
          v-if="currentWebsite"
          :website="currentWebsite"
        />
      </el-tab-pane>
      
      <el-tab-pane label="IP访问查询" name="ip-visits">
        <IpVisits />
      </el-tab-pane>

      <el-tab-pane label="使用教程" name="tutorial">
        <TrackingTutorial />
      </el-tab-pane>
    </el-tabs>

    <!-- 添加网站模态框 -->
    <AddWebsiteModal 
      v-model:visible="modalVisible"
      :is-loading="isLoading"
      @submit="handleCreateWebsite"
    />

    <!-- 嵌入代码模态框 -->
    <EmbedCodeModal 
      v-model:visible="embedModalVisible"
      :embed-code="embedCode"
      @copy="handleCopyEmbedCode"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { ElMessage } from 'element-plus'
import { useTrackingStore } from '@/store/tracking'
import WebsiteTable from './components/WebsiteTable.vue'
import AddWebsiteModal from './components/AddWebsiteModal.vue'
import EmbedCodeModal from './components/EmbedCodeModal.vue'
import StatsDisplay from './components/StatsDisplay.vue'
import BusinessLoopDisplay from './components/BusinessLoopDisplay.vue'
import LogStatsOverview from './components/LogStatsOverview.vue'
import IpVisits from './components/IpVisits.vue'
import TrackingTutorial from './components/TrackingTutorial.vue'
import trackingAPI from '@/api/tracking.api'

// 使用 Pinia Store
const trackingStore = useTrackingStore()

// 使用 storeToRefs 解构响应式状态（保持响应式）
const {
  websites,
  currentWebsite,
  websiteStats,
  logStats,
  statsParams,
  isLoading,
  error
} = storeToRefs(trackingStore)

// 本地 UI 状态
const modalVisible = ref(false)
const embedModalVisible = ref(false)
const embedCode = ref('')
const activeTab = ref('overview')
const initialized = ref(false)

// 初始化数据加载
onMounted(async () => {
  try {
    // 并行加载网站列表和日志统计
    const [websitesData] = await Promise.all([
      trackingStore.fetchWebsites().catch((err: any) => {
        console.error('获取网站列表失败:', err)
        return []
      }),
      trackingStore.fetchLogStats().catch((err: any) => {
        console.error('获取日志统计失败:', err)
        return null
      })
    ])
    
    // 如果有网站数据且没有当前选中的网站，则默认选择第一个
    if (Array.isArray(websitesData) && websitesData.length > 0 && !currentWebsite.value && !initialized.value) {
      initialized.value = true
      trackingStore.setCurrentWebsite(websitesData[0])
      // 不在这里调用fetchWebsiteStats，让watch来处理
    }
  } catch (err) {
    console.error('初始数据加载失败:', err)
    ElMessage.error('获取网站列表失败')
  }
})

// 组件卸载时清理
onUnmounted(() => {
  trackingStore.clearBusinessLoopData()
  // 清理定时器
  if (fetchStatsTimer) {
    clearTimeout(fetchStatsTimer)
  }
})

// 处理错误信息
watch(error, (newError: string | null) => {
  if (newError) {
    ElMessage.error(newError)
    trackingStore.clearError()
  }
})

// 自动拉取当前网站统计数据
let fetchStatsTimer: NodeJS.Timeout | null = null
watch(
  [currentWebsite, statsParams],
  () => {
    // 清除之前的定时器，防止重复请求
    if (fetchStatsTimer) {
      clearTimeout(fetchStatsTimer)
    }
    
    if (currentWebsite.value?._id) {
      // 添加短暂延迟，避免快速切换时的重复请求
      fetchStatsTimer = setTimeout(() => {
        trackingStore.fetchWebsiteStats(currentWebsite.value._id, statsParams.value).catch((err: any) => {
          console.error('获取网站统计数据失败:', err)
        })
      }, 100)
    } else {
      // 如果没有选中网站，清空统计数据
      websiteStats.value = null
    }
  },
  { immediate: true, deep: true }
)

// 事件处理函数
const handleAddWebsite = () => {
  modalVisible.value = true
}

const handleCreateWebsite = async (values: Record<string, any>) => {
  try {
    const newWebsite = await trackingStore.createWebsite(values)
    ElMessage.success('网站创建成功')
    modalVisible.value = false
    // 如果创建成功且有新网站，自动选中并加载统计
    if (newWebsite?._id) {
      trackingStore.setCurrentWebsite(newWebsite)
      activeTab.value = 'overview'
      // 不在这里调用fetchWebsiteStats，让watch来处理
    }
  } catch (err) {
    console.error('创建网站失败:', err)
    ElMessage.error('创建网站失败')
  }
}

const handleUpdateWebsite = async (id: string | number, values: Record<string, any>) => {
  try {
    await trackingStore.updateWebsite(id, values)
    ElMessage.success('网站配置更新成功')
  } catch (err) {
    console.error('更新网站失败:', err)
    ElMessage.error('更新网站失败')
  }
}

const handleDeleteWebsite = async (id: string | number) => {
  try {
    await trackingStore.deleteWebsite(id)
    ElMessage.success('网站删除成功')
  } catch (err) {
    console.error('删除网站失败:', err)
    ElMessage.error('删除网站失败')
  }
}

const handleDeleteAllWebsites = async () => {
  try {
    await trackingStore.deleteAllWebsites()
    ElMessage.success('所有网站删除成功')
  } catch (err) {
    console.error('删除所有网站失败:', err)
    ElMessage.error('删除所有网站失败')
  }
}

const handleGetEmbedCode = async (website: Record<string, any>) => {
  try {
    const response = await trackingAPI.getEmbedCode(website._id)
    // 处理不同的响应格式
    const embedCodeData = response?.data || response || {}
    embedCode.value = embedCodeData.scriptTag || embedCodeData.code || embedCodeData || ''
    embedModalVisible.value = true
  } catch (err: any) {
    console.error('获取嵌入代码失败:', err)
    ElMessage.error('获取嵌入代码失败')
  }
}

const handleCopyEmbedCode = () => {
  navigator.clipboard
    .writeText(embedCode.value)
    .then(() => ElMessage.success('嵌入代码已复制到剪贴板'))
    .catch(() => ElMessage.error('复制失败，请手动复制'))
}

const handleTimeRangeChange = (value: string) => {
  trackingStore.updateStatsParams({ timeRange: value })
}

const handleGroupByChange = (value: string) => {
  trackingStore.updateStatsParams({ groupBy: value })
}

const handleViewStats = (website: Record<string, any>) => {
  if (!website || !website._id) return
  trackingStore.setCurrentWebsite(website)
  activeTab.value = 'overview'
  // 不在这里调用fetchWebsiteStats，让watch来处理
}

const handleViewLogs = (website: Record<string, any>) => {
  if (!website || !website._id) return
  trackingStore.setCurrentWebsite(website)
  // 切换到 IP 访问查询标签页
  activeTab.value = 'ip-visits'
}
</script>

<style scoped lang="scss">
@import './styles.css';
</style>
